﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using Volo.Abp.Application.Services;

namespace Es.Abp.Application.Services
{
    public class AccountService : ApplicationService
    {
        private IHttpContextAccessor _httpContextAccessor;
        public AccountService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        public async Task PostLoginAsync(LoginDto input)
        {
            //校验输入
            //获取用户信息
            //创建token（令牌）

            //抽象，切换，ILoginAuthorizeHandler

            //方式1：SessionLoginAuthorizeHandler
            //  _httpContextAccessor.HttpContext.Session.Set("userId", Encoding.UTF8.GetBytes("用户标识"));
            await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal());




            //方式2：JwtLoginAuthorizeHandler
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("key"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var claims = new List<Claim> { new Claim("userId", "用户标识") };
            var token = new JwtSecurityToken(
               issuer: "xxx",
               audience: "xxx",
               claims: claims,
               expires: DateTime.Now.AddMinutes(10),
               notBefore: DateTime.Now,
               signingCredentials: creds);
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            //返回令牌
        }
        [Authorize]
        public void Get()
        {
            //获取用户信息
            var identities = _httpContextAccessor.HttpContext.User.Identities;
            var userId = identities.First().Claims.Where(x => x.Type == "userId").First();
            //根据用户标识去数据库查询、缓存查询

        }
    }

    public class LoginDto
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}
